<template>
  <div class="dashboard-container">
    <h2 class="head-big-title">Laporan/Analisis</h2>
    <el-date-picker
      v-model="dateTime"
      type="daterange"
      @change="loadData"
      align="right"
      unlink-panels
      format="yyyy-MM-dd"
      value-format="yyyy-MM-dd"
      range-separator="To"
      start-placeholder="start"
      end-placeholder="end">
    </el-date-picker>
    <el-card shadow="always" :body-style="{ padding: '12px 0 12px 20px' }" style="width: 92%;margin: 12px 4% 0 4%;border-radius: 10px;background-color: white;text-align: left;clear: both;">
      <h2 >Jumlah Pesanan</h2>
      <h2 style="font-size: 21px;margin: 6px 0 0 0;color: #e2c439;">{{detailData.totalPOs}}</h2>
    </el-card>
    <el-card shadow="always" :body-style="{ padding: '12px 0 12px 20px' }" style="width: 92%;margin: 12px 4% 0 4%;border-radius: 10px;background-color: white;text-align: left;clear: both;">
      <h2>Jumlah Jualan (MYR)</h2>
      <h2 style="font-size: 21px;margin: 6px 0 0 0;color: #e2c439;">{{ detailData.totalSales?$formatMoneyStr(detailData.totalSales):'RM 0.00' }}</h2>
    </el-card>
    <el-card shadow="always" :body-style="{ padding: '12px 0 12px 20px' }" style="width: 92%;margin: 12px 4% 0 4%;border-radius: 10px;background-color: white;text-align: left;clear: both;">
      <h2>Jumlah Keuntungan (MYR)</h2>
      <h2 style="font-size: 21px;margin: 6px 0 0 0;color: #e2c439;">{{ detailData.totalProfit?$formatMoneyStr(detailData.totalProfit):'RM 0.00' }}</h2>
    </el-card>
    <h2 class="big-title">Jumlah Keuntungan</h2>
    <el-card shadow="always" :body-style="{ padding: '12px 0 12px 20px' }" style="width: 92%;margin: 12px 4% 0 4%;border-radius: 10px;background-color: white;text-align: left;clear: both;">
      <div id="orderChart1" style="width:100%;height:278px;"></div>
    </el-card>
    <h2 class="big-title">Prestasi Jualan dalam Kawasan</h2>
    <el-card shadow="always" :body-style="{ padding: '12px 0 12px 20px' }" style="width: 92%;margin: 12px 4% 0 4%;border-radius: 10px;background-color: white;text-align: left;clear: both;">
      <div id="orderChart2" style="width:100%;height:278px;"></div>
    </el-card>
    <el-card shadow="always" :body-style="{ padding: '12px 0 12px 20px' }" style="width: 92%;margin: 12px 4% 0 4%;border-radius: 10px;background-color: white;text-align: left;clear: both;">
      <el-table
        :data="RegionData"
        :header-cell-style="{'text-align':'center'}">
        <el-table-column prop="regionName" label="Kawasan" align="center">
          <template slot-scope="scope">
            {{ list[scope.row.regionName] }}
          </template>
        </el-table-column>
        <el-table-column prop="totalSales" label="Jumlah Jualan" align="center">
          <template slot-scope="scope">
            {{ scope.row.totalSales?$formatMoneyStr(scope.row.totalSales):'RM 0.00' }}
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <h2 class="big-title">Prestasi Jualan dalam Dealer Utama</h2>
    <el-card shadow="always" :body-style="{ padding: '12px 0 12px 20px' }" style="width: 92%;margin: 12px 4% 0 4%;border-radius: 10px;background-color: white;text-align: left;clear: both;">
      <div id="orderChart3" style="width:100%;height:278px;background-color: white;border-radius: 20px"></div>
    </el-card>
    <el-table
      :data="topMasterData"
      style="width: 92%;margin: 20px 4% 0 4%;padding-left: 10px;border-radius: 20px;">
      <el-table-column prop="dealerName" label="10 Dealer Utama Paling Tinggi" align="center"></el-table-column>
      <el-table-column prop="totalSales" label="Jumlah Jualan" align="center">
        <template slot-scope="scope">
          {{ scope.row.totalSales ? $formatMoneyStr(scope.row.totalSales):'RM 0.00' }}
        </template>
      </el-table-column>
    </el-table>
    <div style="width: 96%;margin: 20px 2% 0 2%;padding-left: 10px;border-radius: 20px;background-color: rgb(245,246,247);text-align: left;">
      <div v-for="(item,index) in allMasterData" :key="index" style="width: 100%;border-radius: 10px;background-color: white;padding: 6px 5px 15px 6px;margin-bottom: 10px;">
        <svg-icon icon-class="ico_view" style="font-size: 24px;float: right;margin-right: 5%;position: relative;bottom: 3px;" @click="toPageMasterDealer(item)" v-if="role == agencyValue"></svg-icon>
        <div style="width: 10px;height: 2px;" v-if="role == agencyValue"></div>
        <el-divider v-if="role == agencyValue"></el-divider>
        <div style="width: 100%;">
          <div style="width: 50%;display: inline-block;">
            <strong>Dealer Utama</strong>
            <p>{{item.dealerName}}</p>
          </div>
          <div style="width: 49%;display: inline-block;">
            <strong>Jumlah Jualan</strong>
            <p>{{ item.totalSales?$formatMoneyStr(item.totalSales):'RM 0.00' }}</p>
          </div>
        </div>
      </div>
    </div>
    <div class="block">
      <el-pagination
        style="float: right;margin: 10px 4% 20px 0"
        :page-size="searchData.pageNum"
        :pager-count="5"
        @current-change="handleCurrentChange"
        :current-page="searchData.pageIndex"
        layout="prev, pager, next"
        :total="totalCount">
      </el-pagination>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { adminReportApi, salesMasterDealerReportApi } from '@/api/user'
import { getDateStr } from '@/utils/auth'
const list = ['Tengah', 'Timur', 'Barat malaysia', 'Utara', 'Selatan']

export default {
  name: 'Report',
  computed: {
    ...mapGetters([
      'name',
      'role'
    ])
  },
  data() {
    return {
      msg: 'Selamat Datang',
      RegionData: [],
      topMasterData: [],
      allMasterData: [],
      totalCount: 0,
      searchData: {
        pageIndex: 1,
        pageNum: 15
      },
      detailData: {},
      list: list,
      orderChart1: '',
      xAxisList: [],
      xAxisLength: [],
      orderChart2: '',
      dateTime: new Date(),
      orderChart3: ''
    }
  },
  mounted() {
    this.checkResetTime()
    this.loadData()
  },
  methods: {
    checkResetTime() {
      const now = new Date()
      let monthStr = now.getMonth() + 1
      let startTime = ''
      let endTime = ''
      endTime = now.getFullYear() + ((monthStr < 10) ? '-0' : '-') + monthStr + '-' + now.getDate()
      startTime = ''
      if (now.getDate() < 10) { // 10日前
        if (monthStr == 1) {
          startTime = (now.getFullYear() - 1) + '-12' + '-' + now.getDate()
        } else {
          monthStr = monthStr - 1
          startTime = now.getFullYear() + ((monthStr < 10) ? '-0' : '-') + monthStr + '-' + now.getDate()
        }
      } else {
        startTime = now.getFullYear() + ((monthStr < 10) ? '-0' : '-') + monthStr + '-1'
      }
      this.dateTime = [startTime, endTime]
    },
    getTimeStrXis() {
      let xAxis = []
      let [startTime, endTime] = this.dateTime
      startTime = new Date(startTime).getTime()
      endTime = new Date(endTime).getTime()
      let dayNum = (endTime - startTime) / 1000 / 60 / 60 / 24
      dayNum = parseInt(dayNum)
      for (let i = 0; i < dayNum; i++) {
        xAxis.push(getDateStr(startTime))
        startTime = startTime + (1000 * 60 * 60 * 24)
      }
      this.xAxisList = xAxis
      // console.log('xAxis', xAxis)
    },
    getXisLength() {
      // let end = 100
      // let [startTime, endTime] = this.dateTime
      // startTime = new Date(startTime).getTime()
      // endTime = new Date(endTime).getTime()
      // let dayNum = (endTime - startTime) / 1000 / 60 / 60 / 24
      // dayNum = parseInt(dayNum)
      this.xAxisLength = [
        {
          type: 'slider',
          show: true,
          xAxisIndex: [0],
          start: 0,
          end: 100
        },
        {
          type: 'inside',
          xAxisIndex: [0],
          start: 0,
          end: 50
        }
      ]
    },
    getFormatChartA(array) {
      const xAxisData = this.spliceProfitData(array)
      return {
        title: {
          subtext: '',
          x: 'left'
        },
        tooltip: {
          trigger: 'axis' // axis   item   none三个值
        },
        dataZoom: this.xAxisLength,
        xAxis: {
          type: 'category', // 还有其他的type，可以去官网喵两眼哦
          data: this.xAxisList, // x轴数据
          name: 'Day' // x轴名称
        },
        yAxis: {
          type: 'value',
          name: 'Sales(MYR)' // y轴名称
        },
        grid: {
          left: '3%',
          right: '3%', // 调整大小
          containLabel: true
        },
        legend: {
          orient: 'vertical',
          x: 'center',
          y: 'top',
          data: ['Sales(MYR)']
        },
        series: [
          {
            name: 'Sales(MYR)',
            type: 'line',
            data: xAxisData
          }
        ]
      }
    },
    getFormatChartB(array) {
      const series = this.spliceRegionData(array)
      return {
        title: {
          subtext: '', // 副标题
          x: 'left' // x轴方向对齐方式
        },
        tooltip: { trigger: 'axis' }, // axis   item   none三个值
        dataZoom: this.xAxisLength,
        xAxis: {
          type: 'category',
          data: this.xAxisList, // x轴数据
          name: 'Day'
        },
        grid: {
          left: '3%',
          right: '3%', // 调整大小
          containLabel: true
        },
        yAxis: { type: 'value', name: 'Sales (MYR)' },
        legend: { orient: 'vertical', x: 'center', y: 'top', data: ['订单量'] },
        series: series
      }
    },
    getFormatChartC(array) {
      const series = this.spliceMasterData(array)
      return {
        title: {
          subtext: '', // 副标题
          x: 'left' // x轴方向对齐方式
        },
        tooltip: { trigger: 'axis' }, // axis   item   none三个值
        dataZoom: this.xAxisLength,
        xAxis: {
          type: 'category',
          data: this.xAxisList, // x轴数据
          name: 'Day'
        },
        grid: {
          left: '3%',
          right: '3%', // 调整大小
          containLabel: true
        },
        yAxis: { type: 'value', name: 'Sales (MYR)' },
        legend: { orient: 'vertical', x: 'center', y: 'top', data: ['Sales (MYR)'] },
        series: series
      }
    },
    spliceProfitData(array) {
      let xAxisTxt = []
      if (array) {
        if (array.length) {
          if (array.length > 0) {
            for (let i = 0; i < array.length; i++) {
              xAxisTxt.push(array[i])
            }
          }
        }
      }
      return xAxisTxt
    },
    spliceRegionData(array) {
      let xAxisData = []
      if (array.length) {
        if (array.length > 0) {
          if (array.length > 0) {
            for (let i = 0; i < array.length; i++) {
              let newList = {
                name: list[array[i].regionName],
                type: 'line',
                data: array[i].details
              }
              xAxisData.push(newList)
            }
          }
        }
      }
      return xAxisData
    },
    spliceMasterData(array) {
      let xAxisData = []
      if (array.length) {
        if (array.length > 0) {
          if (array.length > 0) {
            for (let i = 0; i < array.length; i++) {
              let newList = {
                name: array[i].dealerName,
                type: 'line',
                data: array[i].details
              }
              xAxisData.push(newList)
            }
          }
        }
      }
      return xAxisData
    },
    loadData() {
      this.orderChart1 = this.$echarts.init(document.getElementById('orderChart1'))
      this.orderChart2 = this.$echarts.init(document.getElementById('orderChart2'))
      this.orderChart3 = this.$echarts.init(document.getElementById('orderChart3'))
      this.orderChart1.showLoading()
      this.orderChart2.showLoading()
      this.orderChart3.showLoading()
      const requestData = {
        startTime: this.dateTime[0],
        endTime: this.dateTime[1]
      }
      this.getTimeStrXis()
      this.getXisLength()
      switch (this.role) {
        case this.adminValue:
          adminReportApi(requestData).then(res => {
            this.detailData = res.data
            this.RegionData = res.data.regoinCollect
            this.topMasterData = res.data.masterDealerSales
            this.orderChart1.setOption(this.getFormatChartA(res.data.profitDetail))
            this.orderChart1.hideLoading()
            this.orderChart2.setOption(this.getFormatChartB(res.data.regoinCollect))
            this.orderChart2.hideLoading()
            this.orderChart3.setOption(this.getFormatChartC(res.data.masterDealerSales))
            this.orderChart3.hideLoading()
          }).catch(err => {
            console.log(err)
          })
          this.getMaster_dealerReport()
          break
        case this.agencyValue:
          adminReportApi(requestData).then(res => {
            this.detailData = res.data
            this.RegionData = res.data.regoinCollect
            this.topMasterData = res.data.masterDealerSales
            this.orderChart1.setOption(this.getFormatChartA(res.data.profitDetail))
            this.orderChart1.hideLoading()
            this.orderChart2.setOption(this.getFormatChartB(res.data.regoinCollect))
            this.orderChart2.hideLoading()
            this.orderChart3.setOption(this.getFormatChartC(res.data.masterDealerSales))
            this.orderChart3.hideLoading()
          }).catch(err => {
            console.log(err)
          })
          this.getMaster_dealerReport()
          break
        default:
          this.$message.error('ERROR')
          break
      }
    }, // 得到数据表格 /report/master_dealer/sales
    getMaster_dealerReport() {
      const requestData = this.searchData
      requestData.startTime = this.dateTime[0]
      requestData.endTime = this.dateTime[1]
      // requestData.dealerId = ''
      salesMasterDealerReportApi(requestData).then(res => {
        this.allMasterData = res.data.records
        this.totalCount = res.data.total
      }).catch(err => {
        console.log(err)
      })
    },
    toPageMasterDealer(row) {
      localStorage.setItem('masterdealerId', row.dealerId)
      this.$router.push({ path: '/Reports-Analytics/Dealers' })
    },
    handleCurrentChange(val) {
      this.searchData.pageIndex = val
      this.getMaster_dealerReport()
    }
  }
}

</script>

<style lang="scss" scoped>
.dashboard {
  &-text {
    font-size: 30px;
    line-height: 46px;
  }
}
.head-big-title{
    text-align: left;
    font-size: 20px;
    margin: 20px 0 20px 3%;
  }
.big-title{
  text-align: left;
  font-size: 19px;
  margin: 20px 0 20px 3%;
  clear: both;
}
.dashboard-container{
  margin-top: 20px;
  text-align: center;
}
.two-card + .two-card{
  margin-left: 30px;
}
.two-card{
  width: 300px;
  text-align: left;
  float: left;
  margin-bottom: 30px;

  .title{
    display: block;font-size: 15px;margin: 0;
  }
  .count{
    font-size: 19px;margin: 6px 0 0 0;color: #ffe140;
  }
}
  .last-days-order{
    width: 92%;
    margin: 0 4%;
    border-radius: 20px;
  }
  .last-days-order .erchart-div{
    height:278px;display: inline-block;background-color: white;border-radius: 10px;
  }
</style>
